<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/4
 * Time: 13:11
 */

namespace app\common\service;


use think\Input;
use think\Loader;
use think\Response;

class ImageLoad
{
    protected $uploadDir;
    protected $id = null;
    protected $size='';
    public $path;
    protected static $sizeList = [
        'xs'=>'50,50',
        'l'=>'100,100',
        'b'=>'0,0'//原图大小
    ];
    public $type;
    protected static $typeList = [
        'png'=>'image/png',
        'jpg'=>'image/jpeg'
    ];
    public function init($id , $size ,$type){
        //图片默认上传的路径
        $this->uploadDir = config('img.uploadDir');
        $this->id = $id;
        if(!array_key_exists($size,self::$sizeList)){
            $this->size = 'b';//默认图片尺寸
        }else{
            $this->size = $size;
        }
        if(!array_key_exists($type,self::$typeList)){
            $this->type = 'png';//默认图片类型
        }else{
            $this->type = $type;
        }

        $this->getPath();
    }
    public function __construct($imgId)
    {
        list($id,$size,$type) = explode('_',$imgId,3);

        $this->init($id,$size,$type);
    }

    /**
     * 根据id获取路径
     * @return $this
     * @throws \Exception
     */
    private function getPath(){
        if(is_null($this->id)){
            throw new \Exception('Class image not init!');
        }
        //获取原图路径
        $original = $this->uploadDir.substr($this->id, 0, 2).'/'.substr($this->id, 2);

        //获取尺寸
        $size = explode(',',self::$sizeList[$this->size],2);

        //如果尺寸是原图大小 直接返回原图路径
        if($size[0] == 0){
            $this->path = $original;
        }else{
            //带尺寸的图片路径
            $imgPath = $original.'_'.$size[0].'_'.$size[1];
            //如果该尺寸的图片不存在 则生成一张图片
            if(!is_file($imgPath)){
                //载入Image类
                Loader::import('Image', EXTEND_PATH.'image','.class.php');
                echo EXTEND_PATH.'image';
                $image = new \image\Image();
                $image->open($original);
                $image->thumb($size[0],$size[1],\image\Image::IMAGE_THUMB_CENTER)->save($imgPath);
            }
            $this->path = $imgPath;
        }
        return $this;
    }

    /**
     * 上传图片方法
     * @param $name 上传控件的name值
     * @return array|bool 返回图片的id和类型
     */
    public static function upload($name){
        $file = Input::file($name);
        //获取MD5
        $md5 = md5_file($file->getRealPath());
        //移动到指定的文件夹
        if($file->move(config('img.uploadDir'),substr($md5, 0, 2).'/'.substr($md5, 2))){
            return [
                'id'=>$md5,
                'type' => array_search( $file->getInfo('type') , self::$typeList )
            ];
        }else{
            return false;
        }
    }
    public function printImg(){
        //判断客户端是否有缓存
        /*if($_SERVER['HTTP_IF_MODIFIED_SINCE']){

        }*/
        //判断图片是否存在
        if(is_file($this->path)){
            if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
                if(strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($this->path)){
                    //TODO 浏览器段已经缓存 304
                }
            }
            $im = imagecreatefromjpeg($this->path);
            header('Content-type: '.self::$typeList[$this->type]);
            header("Content-Disposition: inline; filename={$this->id}_{$this->size}.{$this->type}");
            header('Last-Modified: ' . gmdate(DATE_RFC822, filemtime($this->path)));
            header('Date: ' . gmdate("Y-m-d h:i:s",filemtime($this->path)));
            header('Etag','"'.$this->id.'"');
            header("Cache-Control: public, max-age=31536000");
            imagejpeg($im);
            imagedestroy($im);
            return true;
        }else{
            //404
            return null;
        }

    }

}